package com.abu.edums.listener;


import com.abu.pojo.ExcelObject;
import com.abu.pojo.Subject;
import com.abu.edums.service.SubjectService;
import com.abu.exceptionhandler.EduException;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

public class CategoryEventListener extends AnalysisEventListener<ExcelObject> {

    private SubjectService subjectService;

    public CategoryEventListener(SubjectService subjectService) {
        this.subjectService = subjectService;
    }

    /**
     * 每次读取一行
     *
     * @param data
     * @param context
     */
    @Override
    public void invoke(ExcelObject data, AnalysisContext context) {
//        判断是否为空
        if (data == null) {
            throw new EduException(20001, "文件为空");
        }
//      1.获取第一个数据
        String firstData = data.getData01();
//      2.一级分类是否存在
        Subject subject01 = this.isExistSubject01(firstData);
//      3.如果一级分类为空，则新增
        if (subject01 == null) {
            subject01 = new Subject();
            subject01.setParentId("0");
            subject01.setTitle(firstData);
//            新增数据
            this.subjectService.save(subject01);
        }

//      1.获取第二个数据
        String secondData = data.getData02();
//      2.获取一级分类的id
        String firstId = subject01.getId();
        Subject subject02 = this.isExistSubject02(secondData, firstId);
//        如果二级分类为空，则新增
        if (subject02 == null) {
            subject02 = new Subject();
            subject02.setParentId(firstId);
            subject02.setTitle(secondData);
            this.subjectService.save(subject02);
        }
    }

    public Subject isExistSubject01(String title) {
        return this.subjectService.getOne(new QueryWrapper<Subject>().eq("title", title).eq("parent_id", "0"));
    }

    public Subject isExistSubject02(String title, String pid) {
        return this.subjectService.getOne(new QueryWrapper<Subject>().eq("title", title).eq("parent_id", pid));
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }
}
